package com.hmdp.utils;


import cn.hutool.core.lang.UUID;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

public class SimpleRedisLock implements ILock{
    //设置锁的业务名字
    private String name;
    private StringRedisTemplate stringRedisTemplate;
    //设置键值名字
    private static final String KEY_PREFIX="lock:";
    //解决分布式锁误删问题
    private static final String ID_PREFIX= UUID.randomUUID().toString(true)+"-";
    public SimpleRedisLock(String name, StringRedisTemplate stringRedisTemplate) {
        this.name = name;
        this.stringRedisTemplate = stringRedisTemplate;
    }
    //创建静态lua脚本资源
    private static final DefaultRedisScript<Long> UNLOCK_SCRIPT;
    static{
        UNLOCK_SCRIPT=new DefaultRedisScript<>();
        UNLOCK_SCRIPT.setLocation(new ClassPathResource("unlock.lua"));
        UNLOCK_SCRIPT.setResultType(Long.class);
    }


    @Override
    public boolean tryLock(long timeoutSec) {
        //设置redis锁
        //先获取当前线程id作为区分用户键值
        String threadId=ID_PREFIX+Thread.currentThread().getId()+"";
        Boolean success=stringRedisTemplate.opsForValue().setIfAbsent(KEY_PREFIX+name,threadId,timeoutSec, TimeUnit.SECONDS);
        //返回true或者false
        return Boolean.TRUE.equals(success);
    }

    @Override
    public void unlock() {
        //通过lua脚本来解决线程安全问题
        stringRedisTemplate.execute(UNLOCK_SCRIPT,
                Collections.singletonList(KEY_PREFIX+name),
                ID_PREFIX+Thread.currentThread().getId());
    }


    //有线程安全问题
    /*@Override
    public void unlock() {
        //释放锁
        //获取当前线程id作为区分用户键值
        String threadId=ID_PREFIX+Thread.currentThread().getId()+"";
        //再从redis获取当前锁的值判断与当前线程id是否一致
        String id=stringRedisTemplate.opsForValue().get(KEY_PREFIX+name);
        if(threadId.equals(id)){
            //如果一致则删除锁
            stringRedisTemplate.delete(KEY_PREFIX+name);
        }
    }*/
}
